<?php

namespace app\api\logic;

use app\api\service\QuestionService;
use app\common\enum\RedisKeyEnum;
use app\common\exception\BusinessException;
use app\common\model\AiExplanationTask;
use app\common\model\AnswerQuestion;
use app\common\model\AppConfig;
use app\common\model\CollectQuestion;
use app\common\model\Course;
use app\common\model\CoursePaper;
use app\common\model\CourseQuestion;
use app\common\model\CourseQuestionBackground;
use app\common\model\QuestionFeedback;
use app\common\model\UserCourse;
use app\common\model\UserVip;
use app\common\service\ReqLimitService;
use app\common\service\UserService;
use think\facade\Cache;
use think\facade\Config;

class Question
{
    /**
     * getInfo
     * @param $param
     * @return array
     */
    public function getInfo($param): array
    {
        // 提取参数
        $id = $param['id'];
        $userId = $param['userId'] ?? 0;

        // 查询条件
        $where = [
            ['id', '=', $id]
        ];


        // 查询题目数据
        $field = 'id,type,course_id,question_type,question_data,background_id';
        $info = app(CourseQuestion::class)
            ->where($where)
            ->field($field)
            ->find();
        $info = $info ? $info->toArray() : [];

        // 查询题目背景
        if (!empty($info['background_id'])) {
            $where = [['id', '=', $info['background_id']]];
            $info['background_name'] = app(CourseQuestionBackground::class)->where($where)->value('value', '');
        }

        // 查询课程名称
        if (!empty($info['course_id'])) {
            $where = [['id', '=', $info['course_id']]];
            $info['course_name'] = app(Course::class)->where($where)->value('name', '');
        }

        // 查询是否收藏
        $info['isCollection'] = 0;
        if ($userId && $info) {
            $where = [
                ['user_id', '=', $userId],
                ['question_id', '=', $id],
            ];
            $count = app(CollectQuestion::class)->where($where)->count();
            if ($count) {
                $info['isCollection'] = 1;
            }
        }

        // 返回
        return (new QuestionService())->convertData($info);
    }

    /**
     * getNewInfo
     * @param $param
     * @return array
     */
    public function getCount($param): array
    {
        // 提取参数
        $course_id = $param['course_id'];

        // 查询条件
        $where = [
            ['course_id', '=', $course_id]
        ];
        // 查询题目数量
        $count = app(CourseQuestion::class)
            ->where($where)
            ->count();

        // 返回
        return [
            'count' => $count,
            'max_page' => ceil($count / 10),
        ];
    }

    /**
     * 搜索题目
     * @param $param
     * @return mixed
     * @throws
     */
    public function search($param): array
    {
        // 提取参数
        $userId = $param['userId'];
        $keyword = trim($param['keyword'] ?? '');
        $keyword = mb_substr($keyword, 0, 30);

        // 查询字段
        $field = 'id,question_name';

        // 存在关键字则搜索|否则随机取数据
        if ($keyword) {
            // sphinxClient
            $limit = 50;
            $sphinxClient = getSphinxClient();
            $sphinxClient->SetLimits(0, $limit, 100);

            // 精确Like查询
            $res = $sphinxClient->Query('*' . $keyword . '*', 'question');
            $allQuestionId = array_keys($res['matches'] ?? []);

            // 通过Id查询
            $list = [];
            if ($allQuestionId) {
                $where = [['id', 'in', $allQuestionId]];
                $list = app(CourseQuestion::class)->where($where)->field($field)->limit($limit)->select();
                $list = $tempList = $list ? $list->toArray() : [];
                foreach ($list as $key => $val) {
                    if (strpos($val['question_name'], $keyword) === false) {
                        unset($list[$key]);
                    }
                }
                if (!$list) {
                    //$list = $tempList;
                }
            }
        } else {
            $where = [['id', '<', 100]];
            $list = app(CourseQuestion::class)->where($where)->field($field)->limit(5)->select();
            $list = $list ? $list->toArray() : [];
        }

        // 处理question_name
        foreach ($list as $key => $val) {
            $val['question_name'] = strip_tags($val['question_name']);
            $val['question_name'] = mb_substr($val['question_name'], 0, 30);
            $list[$key]['question_name'] = str_replace(['(', ')', '（', '）'], '', $val['question_name']);
        }

        // 搜索扣费
        if ($keyword && $list && !app(UserVip::class)->checkIsVip($userId)) {
            $userService = new UserService();
            $userService->deductScoreToUid($userId, 5, '搜索题库');
        }

        // 返回
        return $list;
    }

    /**
     * 搜索题目
     * @param $param
     * @return mixed
     * @throws
     */
    public function newSearch($param): array
    {
        // 请求参数
        $page = $param['page'] ?? 0;
        $page = max($page, 1);
        $size = $param['size'] ?? 10;
        $userId = $param['userId'];
        $keyword = $param['keyword'];
        $appId = getAppId();
        $ocr_url = $param['ocr_url'] ?? '';

        // 组装配置的搜索方式
        $searchQuestionWay = app(AppConfig::class)->getValueByIdAndTypeWithName(getAppId(), 'search_page_set', 'search_question_way');

        // 根据配置进行数据查询
        $list = $searchQuestionWay == 1 ? $this->searchFromDb($page, $size, $keyword) : $this->searchFromEs($page, $size, $keyword);

        // 用于返回前端的数组
        $newList = [];
        foreach ($list as $key => $item) {

            // 转换题目格式
            $questionData = json_decode($item['question_data'], true);

            // 填充题目类型
            $questionData['id'] = $item['id'];
            $questionData['questionType'] = $item['question_type'];

            // 填充每个选项是否包含正确答案
            $allOptions = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
            foreach ($allOptions as $key) {
                $newKey = 'correct_' . $key;
                $questionData[$newKey] = false;
                if (!empty($questionData['answerOption'][$key]) && strpos($questionData['correctOption'], $key) !== false) {
                    $questionData[$newKey] = true;
                }
            }

            // 解析题目类型
            $questionData['questionTypeName'] = app(CourseQuestion::class)->getQuestionTypeNameByTypeId($item['question_type']);
            $questionData = array_merge($questionData, $questionData['answerOption'] ?? []);
            $newList[] = $questionData;
        }

        // 搜索扣费
        if ($keyword && $newList && !isVip()) {
            $userService = new UserService();
            $userService->deductScoreToUid($userId, 10, '搜索题库');
        }

        // 返回
        return $newList;
    }

    /**
     * searchFromDb
     * @param $page
     * @param $size
     * @param $keyword
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function searchFromDb($page, $size, $keyword): array
    {
        $where = [
            ['question_name', 'like', $keyword . '%']
        ];
        $list = app(CourseQuestion::class)->page($page)->limit($size)->where($where)->select();
        return $list ? $list->toArray() : [];
    }

    private function searchFromEs($page, $size, $keyword)
    {
        // 组装查询参数
        $from = ($page - 1) * $size;
        $params = [
            'index' => 'learn',
            'body' => [
                'query' => [
                    'match' => [
                        'content' => $keyword
                    ],
                ],
                'from' => $from,
                'size' => $size
            ]
        ];
        $client = getEsClient();
        $results = $client->search($params);
        $results->asArray();
        $queryList = $results['hits']['hits'];

        // 查询数据
        $allQuestionId = array_column($queryList, '_id');
        if (!$allQuestionId) {
            return [];
        }
        $where = [['id', 'in', $allQuestionId]];
        $order = buildSqlOrderByField('id', $allQuestionId);
        $list = app(CourseQuestion::class)->where($where)->orderRaw($order)->select();
        return $list;
    }


    /**
     * 搜索题目记录
     * @param $param
     */
    public function searchRecord($param): array
    {
        // 查询数据
        $list = $this->getSearchRecord1();

        // 返回
        return [
            'list' => $list
        ];
    }

    /**
     * getSearchRecord1
     * @return array
     * @throws
     */
    private function getSearchRecord1(): array
    {
        $list = [];
        $time = time();
        $cache = 120;
        $limit = 3;
        $allQuestionId = app(AnswerQuestion::class)->cache($cache)->order('id', 'desc')->limit($limit)->column(
            'question_id'
        );
        if ($allQuestionId) {
            // 查询题目
            $field = 'id,question_name';
            $where = [['id', 'in', $allQuestionId]];
            $questionList = app(CourseQuestion::class)->where($where)->order('id', 'desc')->cache($cache)->field($field)->limit(
                $limit
            )->select();
            $questionList = $questionList ? $questionList->toArray() : [];

            // 填充数据
            foreach ($questionList as $key => $val) {
                $list[$key] = [
                    'nickname' => getRandNickname(),
                    'avatar' => getRandAvatar(),
                    'question_id' => $val['id'],
                    'question_name' => mb_substr(strip_tags($val['question_name']), 0, 12),
                ];
            }
        }

        // 返回
        return $list;
    }

    /**
     * 查询课程题型信息
     * @param $params
     * @return array
     */
    public function getQuestionType($params): array
    {
        // 提取参数
        $id = $params['id'];
        $type = $params['type'];
        $userId = $params['userId'];
        $extendId = $params['extend_id'] ?? 0;

        // 查询条件
        $where = [['course_id', '=', $id]];
        if ($type == 1) {
            $where[] = ['type', '=', $type];
        }
        $cache = false;
        if ($type == 2) {
            // collect_question
            $cache = false;
            $subWhere = [['user_id', '=', $userId], ['course_id', '=', $id], ['status', '=', 1],];
            $subQuestionId = app(CollectQuestion::class)->field('question_id')->where($subWhere)->column('question_id');
            if ($subQuestionId) {
                $where[] = ['id', 'in', $subQuestionId];
            } else {
                $where[] = ['id', '=', -1];
            }
        }
        if ($type == 3) {
            // error_question
            $cache = false;
            $subWhere = [['user_id', '=', $userId], ['course_id', '=', $id], ['status', '=', 2],];
            $subQuestionId = app(AnswerQuestion::class)->where($subWhere)->column('question_id');
            if ($subQuestionId) {
                $where[] = ['id', 'in', $subQuestionId];
            } else {
                $where[] = ['id', '=', -1];
            }
        }
        if ($type == 8) {
            $where[] = ['extend_id', '=', $extendId];
        }

        // 查询数据
        $field = 'question_type,count(*) as count';
        $list = app(CourseQuestion::class)->where($where)->field($field)->group('question_type')->cache(
            $cache
        )->select();
        $list = $list ? $list->toArray() : [];

        // 填充数据
        $limit = Config::get('mcp.default_limit');;
        $type_dict = config('dict.common.question_type');
        foreach ($list as $key => $val) {
            $list[$key]['name'] = $type_dict[$val['question_type']] ?? '---';
            $list[$key]['max_page'] = ceil($val['count'] / $limit);
            $list[$key]['question_type'] = $val['question_type'];
        }

        return $list;
    }

    /**
     * 查询是否继续刷题
     * @param $param
     * @return int[]
     */
    public function isContinue($param): array
    {
        $id = $param['id'];
        $type = $param['type'];
        $userId = $param['userId'];
        $extendId = $param['extend_id'] ?? 0;
        $question_type = $param['question_type'];

        // 查询器
        $queryInput = [
            'id' => $id,
            'type' => $type,
            'userId' => $userId,
            'extendId' => $extendId,
            'questionType' => $question_type
        ];
        $questionService = new QuestionService();
        $query = $questionService->getHistoryQuestionQuery($queryInput);

        // 查询数据
        $lastQuestion = $query->order('u_sec_time', 'desc')->field('question_id,question_page')->find();
        $lastQuestion = $lastQuestion ? $lastQuestion->toArray() : [];

        // 返回
        return [
            'is_continue' => $lastQuestion ? 1 : 0,
            'last_question_id' => $lastQuestion['question_id'] ?? 0,
            'last_question_page' => $lastQuestion['question_page'] ?? 0
        ];
    }

    /**
     * 重置答题记录
     * @param $params
     */
    public function clear($params)
    {
        // 提取参数
        $id = $params['id'];
        $userId = $params['userId'];
        $extend_id = $params['extend_id'];

        // 查询条件
        $where = [
            ['user_id', '=', $userId],
            ['course_id', '=', $id],
        ];
        if ($extend_id > 0) {
            $where[] = ['extend_id', '=', $extend_id];
        }


        // 删除数据
        app(AnswerQuestion::class)->where($where)->delete();

        // 获取Redis实例
        $redis = Cache::store('redis')->handler();

        // 循环推送每个唯一的extend_id到队列
        if ($extend_id == 0) {
            $extendIds = app(CoursePaper::class)->where(['course_id' => $id])->column('id');
        } else {
            $extendIds = [$extend_id];
        }
        foreach ($extendIds as $extendId) {
            $queueData = [
                'uid' => $userId,
                'extend_id' => $extendId,
                'timestamp' => time()
            ];
            $redis->rPush(RedisKeyEnum::USER_ANSWER_QUEUE, json_encode($queueData));
        }
    }

    /**
     * 查询课程题目
     * @param $params
     * @return array
     * @throws BusinessException
     */
    public function getList($params): array
    {
        // 提取参数
        $id = $params['id'];
        $type = $params['type'];
        $page = $params['page'];
        $userId = $params['userId'];
        $limit = Config::get('mcp.default_limit');
        $extendId = $params['extend_id'] ?? 0;
        $questionType = $params['question_type'];

        // 是否课程会员
        $isCourseVip = (new UserCourse())->checkHasCourse($userId, $id);
        if (!$isCourseVip) {
            // 速率限制
            (new ReqLimitService())->check($userId);
        }

        // 查询器
        $field = 'a.id,a.question_type as type,a.question_data,a.background_id,a.extend_id,a.course_id';
        $queryInput = [
            'id' => $id,
            'type' => $type,
            'field' => $field,
            'userId' => $userId,
            'leftAnswer' => false,
            'leftCollect' => false,
            'extendId' => $extendId,
            'questionType' => $questionType,
        ];
        $questionService = new QuestionService();
        $query = $questionService->getQuestionListQuery($queryInput);

        // 查询数据
        $list = $query->page($page)->force('uni_group_question_type')->order('a.id asc')->limit($limit)->select();
        $list = $list ? $list->toArray() : [];

        // 提取相关数据
        if ($list) {
            // 查询题目背景信息
            $backgroundId = array_column($list, 'background_id');
            $backgroundId = array_filter($backgroundId);
            if ($backgroundId) {
                $backgroundList = $questionService->getQuestionBackgroundByContentId($backgroundId);
            } else {
                $backgroundList = [];
            }

            // 查询收藏信息
            $questionId = array_column($list, 'id');
            $collectQuestionDict = [];
            if ($questionId) {
                $collectQuestionDict = $questionService->getUserCollectQuestionDict($userId, $questionId);
            }

            // 查询错题信息
            $errorQuestionDict = [];
            if ($questionId) {
                $errorQuestionDict = $questionService->getUserErrorQuestionDict($userId, $questionId, $type);
            }
        }

        //组装数据
        foreach ($list as $key => $value) {
            // 是否答错题目
            $value['is_correct'] = $errorQuestionDict[$value['id']]['status'] ?? 0;
            $value['select_answer'] = $errorQuestionDict[$value['id']]['question_answer'] ?? '';

            // 是否收藏题目
            $value['isCollection'] = $collectQuestionDict[$value['id']]['status'] ?? 0;

            // 添加题目类型名称
            $value['type_name'] = app(CourseQuestion::class)->getQuestionTypeMap()[$value['type']] ?? '-';

            //1.合并数组
            $value = array_merge($value, json_decode($value['question_data'], true));

            //2.如果是选择题,将选项提取出来
            if (!empty($value['answerOption'])) {
                $value = array_merge($value, $value['answerOption']);
            }

            //4.清理数据
            unset($value['question_data'], $value['answerOption']);

            //5.错题、收藏题答题记录设置为空,并且设置未答过
            if (in_array($type, [2, 3])) {
                $value['select_answer'] = '';
                $value['is_correct'] = 0;
            }

            //6.记录page
            $value['page'] = $page;

            //7.处理Img Style
            $value['question_images'] = $value['questionImgList'] ?? [];
            unset($value['questionImgList']);

            //8.ai解析
            $value['aiExplanation'] = $value['aiExplanation'] ?? '';

            //8.组装数据
            $this->formatQuestionImgText($value);
            $list[$key] = $value;
        }

        // 试卷积分扣除
        if ($type == 8 && $extendId > 0 && !$isCourseVip && $list) {
            $paperInfo = app(CoursePaper::class)->where(['id' => $extendId])->find();
            if ($paperInfo) {
                if ($paperInfo['is_need_vip']) {
                    throw new BusinessException('此试卷需要先开通题库');
                }
                if ($paperInfo['integral_price'] > 0) {
                    $remark = '试卷练习';
                    $userService = new UserService();
                    $userService->deductScoreToUid($userId, $paperInfo['integral_price'], $remark);
                }
            }
        }

        // 返回
        return [
            'question_list' => $list,
            'question_background' => $backgroundList ?? [],
        ];
    }

    /**
     * 查询答题卡
     * @param $params
     * @return array
     * @throws BusinessException
     */
    public function getAnswerCard($params): array
    {
        // 提取参数
        $id = $params['id'];
        $type = $params['type'];
        $userId = $params['userId'];
        $extendId = $params['extend_id'] ?? 0;
        $questionType = $params['question_type'];

        // 是否课程会员
        $isCourseVip = (new UserCourse())->checkHasCourse($userId, $id);
        if (!$isCourseVip) {
            // 速率限制
            (new ReqLimitService())->check($userId);
        }

        // 查询器
        $field = 'a.id,IFNULL(c.status,0) as is_correct,c.question_answer as status';
        $queryInput = [
            'id' => $id,
            'type' => $type,
            'field' => $field,
            'userId' => $userId,
            'leftAnswer' => true,
            'leftCollect' => false,
            'extendId' => $extendId,
            'questionType' => $questionType,
        ];
        $questionService = new QuestionService();
        $query = $questionService->getQuestionListQuery($queryInput);

        // 查询数据
        $list = $query->force('uni_group_question_type')->order('a.id asc')->select();
        $list = $list ? $list->toArray() : [];

        // 组装数据
        $answerCard = [
            'right_count' => 0,
            'error_count' => 0,
            'answered_count' => 0,
            'no_answer_count' => 0,
            'answer_card' => [],
        ];
        foreach ($list as $key => $value) {
            $answerCard['answer_card'][] = [
                'id' => $value['id'],
                'index' => $key + 1,
                'status' => $value['is_correct'] ?? 0,
            ];
            if ($value['is_correct'] == 1) {
                $answerCard['right_count']++;
            }
            if ($value['is_correct'] == 2) {
                $answerCard['error_count']++;
            }
            if ($value['is_correct'] == 0) {
                $answerCard['no_answer_count']++;
            }
            if ($value['is_correct'] != 0) {
                $answerCard['answered_count']++;
            }
        }

        // 返回
        return $answerCard;
    }


    /**
     * 收藏题目
     * @param $param
     * @throws
     */
    public function collect($param)
    {
        //提取参数
        $id = $param['id'];
        $type = $param['type'];

        //查询题目信息
        $field = 'id,course_id';
        $info = app(CourseQuestion::class)->where(['id' => $id])->field($field)->find();
        $info = $info ? $info->toArray() : [];
        if (!$info) {
            throw new BusinessException('题目信息不存在');
        }

        //组装数据
        $time = time();
        $data = [
            'user_id' => $param['userId'],
            'course_id' => $info['course_id'],
            'question_id' => $info['id'],
            'status' => $type,
            'a_time' => $time,
            'u_time' => $time,
        ];
        $result = app(CollectQuestion::class)->replace(true)->save($data);
        if ($result === false) {
            throw new BusinessException('报考或者取消课程失败');
        }
    }

    /**
     * 评论题目
     * @param $param
     */
    public function comment($param)
    {
        // 提取参数
        $id = $param['id'];
        $content = $param['content'];
    }

    /**
     * 保存答题记录
     * @param $param
     * @throws BusinessException
     */
    public function saveAnswer($param)
    {
        // 提取参数
        $userId = $param['userId'];
        $answer_data = $param['answer_data'];
        $source = $param['source'] ?? 0;

        // 循环组装数据
        foreach ($answer_data as $val) {
            $model = new AnswerQuestion();
            $model->startTrans();

            // 组装数据
            $saveData = [
                'course_id' => $val['course_id'],
                'extend_id' => $val['extend_id'],
                'question_id' => $val['question_id'],
                'question_type' => $val['question_type'],
                'question_page' => $val['question_page'],
                'question_answer' => $val['question_answer'],
                'question_main_type' => $source,
                'user_id' => $userId,
                'status' => $val['question_correct'],
                'u_sec_time' => getMicrosecondTimestamp()
            ];

            // 查询是否存在
            $where = [
                'user_id' => $userId,
                'course_id' => $val['course_id'],
                'question_id' => $val['question_id'],
                'question_main_type' => $source,
            ];
            $count = $model->where($where)->count();
            if ($count) {
                // 更新数据
                $isUpdate = $model->save_data(
                    $saveData,
                    $where
                );
                if ($isUpdate === false) {
                    throw new BusinessException("数据保存失败");
                }
            } else {
                // 新增数据
                $isInsert = $model->add_data($saveData);
                if ($isInsert === false) {
                    throw new BusinessException("数据保存失败");
                }
            }
            $model->commit();
        }

        // 提取所有extend_id并去重
        $extendIds = array_filter(array_unique(array_column($answer_data, 'extend_id')));

        // 获取Redis实例
        $redis = Cache::store('redis')->handler();

        // 循环推送每个唯一的extend_id到队列
        foreach ($extendIds as $extendId) {
            $queueData = [
                'uid' => $userId,
                'extend_id' => $extendId,
                'timestamp' => time()
            ];

            // 写入队列
            $redis->rPush(RedisKeyEnum::USER_ANSWER_QUEUE, json_encode($queueData));
        }
    }

    /**
     * answerResult
     * @param $param
     * @return array
     */
    public function answerResult($param): array
    {
        // 提取参数
        $id = $param['id'];
        $type = $param['type'];
        $userId = $param['userId'];
        $extendId = $param['extend_id'] ?? 0;
        $questionType = $param['question_type'];

        // 查询总数
        $queryInput = [
            'id' => $id,
            'type' => $type,
            'field' => [],
            'userId' => $userId,
            'leftAnswer' => true,
            'leftCollect' => true,
            'extendId' => $extendId,
            'questionType' => $questionType,
        ];
        $questionService = new QuestionService();
        $query1 = $query2 = $query3 = $questionService->getQuestionListQuery($queryInput);
        $allCount = $query1->count();

        // 查询已回答数
        $answerCount = $query2->where('c.id > 0')->count();

        // 查询回答正确数
        $rightCount = $query3->where('c.status = 1')->count();

        // 返回
        return [
            'all_count' => $allCount,
            'answer_count' => $answerCount,
            'right_count' => $rightCount,
            'right_rate' => $answerCount ? round(($rightCount / $answerCount), 2) * 100 : 0,
        ];
    }

    /**
     * 提交反馈
     * @param $param
     */
    public function feedback($param)
    {
        // 提取参数
        $userId = $param['userId'] ?? 0;
        $content = $param['content'] ?? '';
        $detail = $param['detail'] ?? '';
        $question_id = $param['question_id'];

        // 构建内容
        $time = time();
        $questionService = new QuestionService();
        $data = [
            'uid' => $userId,
            'course_id' => $questionService->getCourseIdByQuestionId($question_id),
            'question_id' => $question_id,
            'content' => $content ?: $detail,
            'create_time' => $time,
            'update_time' => $time,
        ];

        // 提交数据
        app(QuestionFeedback::class)->add_data($data);
    }


    /**
     * formatQuestionImgText
     * @param &$value
     */
    private function formatQuestionImgText(&$value)
    {
        $value['question_images'] = 1;
        $fields = [
            'A',
            'B',
            'C',
            'D',
            'E',
            'F',
            'explanation',
            'questionAsk',
            'correctOption'
        ];
        foreach ($fields as $field) {
            if (!isset($value[$field])) {
                continue;
            }
            if ($value[$field] == '') {
                continue;
            }
            if (strpos($value[$field], 'img') !== false) {
                $html = $value[$field];
                $html = str_replace('file.gaojiufeng.cn', 'file.20230611.cn', $html);
                try {
                    libxml_use_internal_errors(true);
                    $doc = new \DOMDocument();
                    @$doc->loadHTML($html);

                    // 循环img标签
                    foreach ($doc->getElementsByTagName('img') as $link) {
                        // 提取到图片的Src
                        $src = $link->getAttribute('src');

                        $src = str_replace('file.gaojiufeng.cn', 'file.20230611.cn', $src);

                        // 提取原来的html
                        $oldImgHtml = $doc->saveHtml($link);

                        // 生成新的html
                        $newImgHtml = <<<EOL
   <img src="{$src}" style="width: 100%;height: auto" />
EOL;
                        $html = str_replace($oldImgHtml, $newImgHtml, $html);
                        $value['question_images'][] = $src;
                    }
                } catch (\Exception $exception) {
                }
                $value[$field] = $html;
            }
        }
    }

    /**
     * aiExplanation
     * @param $param
     * @return mixed
     * @throws
     */
    public function aiExplanation($param)
    {
        // 提取参数
        $id = $param['id'];
        $userId = $param['userId'];

        // 检查题目编号
        $info = app(CourseQuestion::class)->find($id);
        if (!$info) {
            throw new BusinessException('题目不存在或已被删除');
        }

        // 题目反序列化检查是否有答案
        $infoData = json_decode($info['question_data'], true);
        if ($infoData['correctOption'] == '') {
            throw new BusinessException('题目正确答案缺失不支持解析');
        }

        // 检查是否生成任务
        $where = [['question_id', '=', $id]];
        $task = app(AiExplanationTask::class)->where($where)->find();
        if ($task) {
            if ($task['status'] == 1) {
                throw new BusinessException('后台正在解析中');
            }
            if ($task['status'] == 3) {
                throw new BusinessException('此题目解析失败');
            }

            // 成功解析扣除积分
            if (!isVip()) {
                $score = 10;
                $remark = 'AI解析';
                $userService = new UserService();
                $userService->deductScoreToUid($userId, $score, $remark);
            }

            // 返回
            return [
                'business_code' => 2, // 表示解析生成成功
                'business_message' => $task['answer'],
            ];
        }

        // 生成任务
        $time = time();
        $saveData = [
            'app_id' => getAppId(),
            'uid' => $userId,
            'question_id' => $id,
            'ask' => '',
            'answer' => '',
            'error' => '',
            'create_time' => $time,
            'update_time' => 0,
        ];
        app(AiExplanationTask::class)->add_data($saveData);

        // 返回
        return [
            'business_code' => 1, // 表示正在生成解析
            'business_message' => '',
        ];
    }
}
